package com.lai.hospital.handler;

import com.lai.hospital.constant.SecurityConst;
import com.lai.hospital.entity.Collect;
import com.lai.hospital.exception.BizException;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

import static com.lai.hospital.constant.SecurityConst.INSUFFICIENT_PRIVILEGES;

/**
 * @author : lai
 * @version V1.0
 * @Project: hospital-springboot
 * @Package com.lai.hospital.handler
 * @Description: 访问决策管理器    做出最终的访问控制（授权）决定。
 * 所有当前请求需要的 ConfigAttributes ，全部交给 AccessDecisionVoter 进行投票。
 * 只要任一 AccessDecisionVoter 授予访问权限，便返回，不再继续决策判断。否则，便抛出访问授权拒绝的异常，
 * @date Date : 2022年11月18日 14:50
 */
//@Component
//public class AccessDecisionManagerImpl implements AccessDecisionManager {
//    @Override
//    public void decide(Authentication authentication, Object o, Collection<ConfigAttribute> collection) throws AccessDeniedException, InsufficientAuthenticationException {
//        // 获取用户权限列表
//        List<String> permissionList = authentication.getAuthorities()
//                .stream()
//                .map(GrantedAuthority::getAuthority)
//                .collect(Collectors.toList());
//        for (ConfigAttribute item : collection) {
//            if (permissionList.contains(item.getAttribute())) {
//                return;
//            }
//        }
//        throw new AccessDeniedException("没有操作权限");
//    }
//
//    @Override
//    public boolean supports(ConfigAttribute configAttribute) {
//        return true;
//    }
//
//    @Override
//    public boolean supports(Class<?> aClass) {
//        return true;
//    }
//}
@Component
public class AccessDecisionManagerImpl implements AccessDecisionManager {
    @Override
    public void decide(Authentication authentication, Object o, Collection<ConfigAttribute> collection) throws AccessDeniedException, InsufficientAuthenticationException {
        // 获取用户权限列表
        List<String> permissionList = authentication.getAuthorities()
                .stream()
                .map(GrantedAuthority::getAuthority)
                .collect(Collectors.toList());
        for (ConfigAttribute item : collection) {
            if (permissionList.contains(item.getAttribute())) {
                return;
            }
        }
        throw new AccessDeniedException(INSUFFICIENT_PRIVILEGES);
    }

    @Override
    public boolean supports(ConfigAttribute configAttribute) {
        return true;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}